var utils = require('../../../utils/utils.js'),
appData = getApp().globalData,
app = getApp(),
Url = 'login/';
Page({
  data: {
    newer: false,
  },
  onLoad: function (e) {
    wx.clearStorage();
    wx.clearStorageSync();
    var that = this;
    wx.login({
      success: function (res) {
        let note = 'Prepare global info';
        app.request(Url + 'getRegInfo', { code: res.code }, note).then((res) => {
          const r = res.data;
          console.log(res.name, r);
          appData.user.openid = r.openid;  // 先存储 openID
          if (r.hotel) {
            var hotels = r.hotel.split(',');
            for (let i = 0; i < hotels.length; i++) 
              if (parseInt(hotels[i].split(':')[0]) == appData.hotel) {
                that.getMyHotelInfo(hotels[i].split(':')[1]);
                that.getAdminInfo(appData.user.openid);
                return 0;
              }
            var params = 'newer=0&hotel=' + r.hotel + '&key=' + r.session_key 
            wx.redirectTo({ url: '../register/register?' + params});
          } else 
            wx.redirectTo({ url: '../register/register?newer=1&key=' + r.session_key });
        })
      }
    })
  },

  getMyHotelInfo: function (id) {
    const that = this;
    let note = 'Prepare hotel info';
    app.request(Url + 'login', { id: id }, note).then((info) => {
      console.log('user:', info.data.user);
      console.log('share:', info.data.share);
      console.log('receive:', info.data.receive);
      appData.share = info.data.share;
      appData.user = info.data.user;
      appData.receive = info.data.receive;
      if (!appData.share.total) appData.share.total = parseFloat("0").toFixed(2)
      wx.reLaunch({ url: '../index/index' });
    })
  },

  getAdminInfo: function (id) {
    app.request('admin/loginAdmin', { id: id }).then((info) => {
      appData.admin = info.data;
    })
  },

  onShareAppMessage: function () {

  },
})